﻿using System;
using Bulb.Core.Services.CollectionService.Messages;
using Bulb.Core.Services.DataStore;
using System.Collections.Generic;
using Cirrious.MvvmCross.Plugins.Messenger;

namespace Bulb.Core.Services.CollectionService
{
    public class CollectionService : ICollectionService
    {
        private readonly IRepository<BulbItem> _bulbItemRepository;
        private readonly IMvxMessenger _messenger;

        public CollectionService(IRepository<BulbItem> bulbItemRepository, IMvxMessenger messenger)
        {
            _bulbItemRepository = bulbItemRepository;
            _messenger = messenger;
        }

        public IList<BulbItem> All()
        {
            return _bulbItemRepository.All();
        }

        public BulbItem Latest
        {
            get
            {
                return _bulbItemRepository.Latest(bulbItem => bulbItem.DateTime);
            }
        }

        public BulbItem Get(int id)
        {
            return _bulbItemRepository.Get(id);
        }

        public void Add(BulbItem bulbItem)
        {
           _bulbItemRepository.Add(bulbItem);
           _messenger.Publish(new CollectionChangedMessage(this));
        }

        public void Delete(BulbItem bulbItem)
        {
            _bulbItemRepository.Delete(bulbItem);
            _messenger.Publish(new CollectionChangedMessage(this));
        }
        
        public void Update(BulbItem bulbItem)
        {
            _bulbItemRepository.Update(bulbItem);

            _messenger.Publish(new ItemChangedMessage(this));
            _messenger.Publish(new CollectionChangedMessage(this));
        }
        
        public void On(BulbItem bulbItem)
        {
            bulbItem.State = true;
        }

        public void Off(BulbItem bulbItem)
        {
            bulbItem.State = false;
        }

        BulbItem IRepository<BulbItem>.Latest(Func<BulbItem, object> func)
        {
            return _bulbItemRepository.Latest(func);
        }

        public List<BulbItem> Filter(Func<BulbItem, bool> func)
        {
            return _bulbItemRepository.Filter(func);
        }

        public int Count()
        {
            return _bulbItemRepository.Count();
        }

        public void Dispose()
        {
            
        }
    }
}
